package com.luojialong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojialong.enums.AffairStatus;
import com.luojialong.exception.AffairException;
import com.luojialong.model.domain.User;
import com.luojialong.service.UserService;
import com.luojialong.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

import static com.luojialong.constant.UserRank.USER_LOGIN_KEY;

/**
 * @author 罗家龙
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-04-21 15:30:01
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 用户注册
     *
     * @param userAccount   用户的账号
     * @param userPassword  用户密码
     * @param checkPassword 用户校验密码
     * @return 新建用户的id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号或密码,校验密码为空");
        }
        if (userAccount.length() < 8) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号的长度不得小于8");
        }
        if (userPassword.length() < 10 || userPassword.length() > 18 || checkPassword.length() < 10) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码长度不得小于10,且不得大于18");
        }
        String rule = "^(?![a-zA-Z]+$)(?!\\d+$)(?![^\\da-zA-Z\\s]+$).{10,18}$";
        if (!userPassword.matches(rule)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR,"密码必须包括数字,或字母,特殊符号,其中的两种组成");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR,"两次输入的密码都不一致");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new AffairException(AffairStatus.PARAMS_ERROR,"该账号已经存在了");
        }
        String md5Password = DigestUtils.md5DigestAsHex((userAccount + userPassword).getBytes(StandardCharsets.UTF_8));
        User addUser = new User();
        addUser.setUserAccount(userAccount);
        addUser.setUserPassword(md5Password);
        boolean save = this.save(addUser);
        if (!save) {
            throw new AffairException(AffairStatus.FAILURE,"注册失败,系统内部问题");
        }
        return addUser.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户的账号
     * @param userPassword 用户密码
     * @return 返回脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            //修改为自定义异常
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号或密码为空");
        }
        if (userAccount.length() < 8) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号的长度不得小于8");
        }
        if (userPassword.length() < 10 || userPassword.length() > 18) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码长度不得小于10,且不得大于18");
        }
        String rule = "^(?![a-zA-Z]+$)(?!\\d+$)(?![^\\da-zA-Z\\s]+$).{9,18}$";
        if (!userPassword.matches(rule)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR,"密码必须包括数字,或字母,特殊符号,其中的两种组成");
        }
        String md5Password = DigestUtils.md5DigestAsHex((userAccount + userPassword).getBytes(StandardCharsets.UTF_8));
        QueryWrapper<User> userLoginWrapper = new QueryWrapper<>();
        userLoginWrapper.eq("userAccount", userAccount);
        userLoginWrapper.eq("userPassword", md5Password);
        User loginUser = this.getOne(userLoginWrapper);
        if (loginUser == null) {
            log.info("user login failed : userAccount or userPassword is error");
            throw new AffairException(AffairStatus.PARAMS_ERROR,"登录失败用户,账号或密码不匹配");
        }
        User safetyUser = getSafetyUser(loginUser);
        request.getSession().setAttribute(USER_LOGIN_KEY, safetyUser);
        return safetyUser;
    }

    @Override
    public User getSafetyUser(User loginUser) {
        if (loginUser == null) {
            return null;
        }
        //脱去敏感用户信息
        User safetyUser = new User();
        safetyUser.setId(loginUser.getId());
        safetyUser.setUsername(loginUser.getUsername());
        safetyUser.setUserAccount(loginUser.getUserAccount());
        safetyUser.setAvatarUrl(loginUser.getAvatarUrl());
        safetyUser.setRole(loginUser.getRole());
        safetyUser.setGender(loginUser.getGender());
        safetyUser.setPhone(loginUser.getPhone());
        safetyUser.setEmail(loginUser.getEmail());
        safetyUser.setCreateTime(loginUser.getCreateTime());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request 请求
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_KEY);
        return 1;
    }

    /**
     * 获取已经登录的用户信息
     * @param request 请求
     * @return 返回已经登录的用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(USER_LOGIN_KEY);
    }

}




